import axios from '@/utils/request'
export default {
  Product: {
    form: {
      fields: [
        'name',
        {
          property: 'category',
          field_options: { label: '类型' },
          component: {
            props: ['form', 'property'],
            data() {
              return {
                categories: []
              }
            },
            created() {
              this.axios.get(`/manage/categories`, {
                params: {
                  '@filter': '!entity.getParent() && entity.getType().getSlug() == "ProductCategory" ',
                  '@expands': `['entity.children']`
                }
              }).then((res) => {
                console.log('category', res.data)
                for (let i of res.data) {
                  for (let c in i.children) {
                    if (i.children[c].__metadata.type.id != 1) {
                      i.children.splice(c,1)
                    }
                  }
                }
                this.categories = res.data
              })
            },
            render(h) {
              return (
                <el-select v-model={this.form[this.property]} filterable placeholder='类型'>{
                  this.categories.map(type => {
                    return <el-option-group label={type.name} key={type.id} value={type.id}>
                      {
                        type.children.map(category => {
                          return <el-option key={category.id} label={category.__toString} value={category.id} />
                        })
                      }
                    </el-option-group>
                  })
                }</el-select>
              )
            }
          }
        },
        {
          property: 'tags',
          field_options: { label: '标签' },
          required: false,
          component: {
            props: ['form', 'property'],
            data() {
              return {
                parentId: null,
                tags: []
              }
            },
            watch: {
              'form.category': {
                handler(value, oldValue) {
                  if (!value) return

                  this.axios.get(`/manage/categories/${value}`)
                    .then(res => {
                      if (this.parentId !== res.data.parent.id) {
                        this.parentId = res.data.parent.id
                        this.tags = []

                        // Load tags based on selected category
                        this.axios.get(`/manage/tags`, {
                          params: {
                            '@filter': `entity.getCategory().getParent().getId() == ${this.parentId}`,
                            '@expands': "['entity.category']"
                          }
                        }).then((res) => {
                          this.tags = res.data
                        })
                      }
                    })
                },
                immediate: true
              }
            },
            render(h) {
              if (this.tags && this.tags.length > 0) {
                return (
                  <el-select v-model={this.form[this.property]} v-loading={!this.tags.length} multiple placeholder='类型' style='width:250px'>{
                    this.tags.map(tag => {
                      return <el-option key={tag.id} label={`${tag.category.__toString}-${tag.name}`} value={tag.id} />
                    })
                  }</el-select>
                )
              } else {
                return (
                  <div>该类型暂无标签分类</div>
                )
              }
            }
          }
        },
        { property: 'isOnSale', default_value: true },
        { property: 'isRecommended', default_value: true },
        { property: 'indexCover', type: 'image', field_options: { label: '首页封面图' }, help: '只会在设置了首页产品时候显示' },
        { property: 'cover', type: 'image' },
        { property: 'pictures', type: 'images' },
        'spu',
        { property: 'productStandardNumber', field_options: { label: '产品标准号' } },
        { property: 'shelfLife', field_options: { label: '保质期' } },
        { property: 'factoryName', field_options: { label: '工厂名' } },
        { property: 'factoryAddress', field_options: { label: '工厂地址' } },
        { property: 'foodAdditives', field_options: { label: '食品添加剂' } },
        { property: 'ingredientList', field_options: { label: '配料表' } },
        { property: 'manufacturerContactInformation', field_options: { label: '厂家联系方式' } },
        { property: 'manufacturingLicenseNumber', field_options: { label: '生产许可证编号' } },
        { property: 'manufacturingDate', field_options: { label: '生产日期' } },
        { property: 'storageMethod', field_options: { label: '储存方法' } },
        // { property: 'price', field_options: { label: '销售价' } },
        // { property: 'marketPrice', field_options: { label: '市场价' } },
        { property: 'listOrder', default_value: 255 },
        { property: 'description', field_options: { label: '产品详情' } }
      ]
    },
    list: {
      // export: {
      //   query: {
      //     '@display': `{
      //       'stock' : 'entity.getStock().getSpecification().getName()',
      //       'quantity' : 'entity.getQuantity()',
      //       'unitPrice' : 'entity.getUnitPrice()',
      //       'comment' : 'entity.getComment()',
      //       'cretedTime' : 'entity.getCreatedTime().format("Y-m-d H:i:s")'
      //     }`,
      //     limit: 10000000
      //   },
      //   label: {
      //     'stock': '产品',
      //     'quantity': '数量',
      //     'unitPrice': '单价',
      //     'comment': '原因',
      //     'cretedTime': '时间'
      //   }
      // },
      // actions: [
      //   {
      //     name: '导入',
      //     position: 'top',
      //     component:
      //       () => import('@/views/product/synchronous.vue')
      //   }
      // ],
      query: {
        '@order': 'entity.id|DESC',
        // '@filter': `entity.getCategory().getType().getSlug() == 'ProductCategory'`,
        '@display': `{
          'id' : 'entity.getId()',
          'name': 'entity.getName()',
          'category': 'entity.getCategory()',
          'parentCategory': 'entity.getCategory() ? entity.getCategory().getParent().getName() : ""',
          'cover': 'entity.getCover()',
          'isOnSale': 'entity.getIsOnSale()',
          'isRecommended': 'entity.getIsRecommended()',
          'specifications': 'entity.getSpecifications()',
          'listOrder': 'entity.getListOrder()',
          'spu': 'entity.getSpu()',
          'tags': 'entity.getTags()'
        }`
      },
      list_filter: {
        'noneSpecification': {
          expression: 'entity.getSpecifications().count() == 0',
          label: '无规格产品',
          type: 'boolean'
        },
        'name': '名称',
        'category.id': () => {
          return axios
            .get('/api/categories',
              { params: { '@filter': 'entity.getParent() && entity.getType().getSlug() == "ProductCategory"', '@expands': "['entity.parent']" } })
            .then(res =>
              Object.assign(
                { __label: '产品分类' },
                ...res.data.map(v => { return { [v.id]: `${v.name}(${v.parent.__toString})` } })
              )
            )
        }
      },
      list_display: [
        // 'id',
        { property: 'name', editable: true },
        { property: 'parentCategory', label: '上级分类' },
        { property: 'category', label: '类型' },
        // {
        //   property: 'spu',
        //   editable: true,
        //   label: '产品编码'
        // },
        { property: 'cover', type: 'image' },
        { property: 'isOnSale', editable: true, label: '上架' },
        { property: 'isRecommended', editable: true, label: '推荐' },
        { property: 'spu', editable: true, label: '产品编码' },
        {
          property: 'specifications',
          label: '规格',
          component: {
            props: ['data'],
            render(h) {
              return (
                <div>
                  {
                    this.data.map(v => {
                      return <p>{v.name}<span style='color:red'>(￥{v.price})</span></p>
                    })
                  }
                </div>
              )
            }
          }
        },
        // {
        //   property: 'tags',
        //   label: '标签',
        //   component: {
        //     props: ['data'],
        //     render(h) {
        //       if (this.data && this.data.length > 0) {
        //         return (
        //           <span>{this.data.toString()}</span>
        //         )
        //       }
        //     }
        //   }
        // },
        { property: 'listOrder', editable: true }
      ]
    }
  }
}
